package com.yun.zf.admin.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yun.zf.admin.mapper.ZfCommunityPictureMapper;
import com.yun.zf.admin.service.ZfCommunityPictureService;
import com.yun.zf.common.admin.dto.community.CommunityPictureDto;
import com.yun.zf.common.app.domain.ZfCommunityPicture;
import com.yun.zf.common.constant.Constants;
import com.yun.zf.common.vo.Response;
import com.yun.zf.system.utils.AliyunOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 社区环境图片表 服务实现类
 * </p>
 *
 * @author cj
 * @since 2021-01-29
 */
@Service
@Slf4j
public class ZfCommunityPictureServiceImpl extends ServiceImpl<ZfCommunityPictureMapper, ZfCommunityPicture> implements ZfCommunityPictureService {

    @Autowired
    private AliyunOssUtil ossUtil;
    @Autowired
    private ZfCommunityPictureMapper communityPictureMapper;

    /**
     * 保存图片
     *
     * @param
     * @return
     */
    @Override
    public Long addCommunityPic(ZfCommunityPicture picture) {

        baseMapper.insert(picture);
        return picture.getId();

    }

    /**
     * 获取图片信息
     *
     * @param communtyId
     * @return
     */
    @Override
    public List<CommunityPictureDto> getCommunityPicture(Long communtyId, int type) {

        return baseMapper.getPictureByCid(communtyId, type);
    }

    /**
     * 删除图片
     *
     * @param ids
     * @return
     */
    @Override
    @Transactional
    public Response delCommunityPicture(String ids) {
        try {
            //1、 查询图片列表信息
            List<Long> idlist = Arrays.asList(ids.split(",")).parallelStream().map(a->Long.parseLong(a.trim())).collect(Collectors.toList());
            QueryWrapper<ZfCommunityPicture> communityPictureQueryWrapper = new QueryWrapper<>();
            communityPictureQueryWrapper.in("id", idlist);
            List<ZfCommunityPicture> list = baseMapper.selectList(communityPictureQueryWrapper);
            //2、删除oss 图片
            for (ZfCommunityPicture pic : list
            ) {
                //1、删除oss 中的图片资源
                ossUtil.deleteFile(Constants.BUCKET_COMMUNITY, pic.getPath());
            }
            int cn = baseMapper.deleteBatchIds(idlist);
            if (cn > 0) {
                return Response.success("删除成功");
            }
            return Response.error("删除失败");
        } catch (Exception e) {
            return Response.error("删除失败");
        }
    }


    @Override
    public int delCommunityPicture(Long communtyId, int type) {
        QueryWrapper<ZfCommunityPicture> communityPictureQueryWrapper = new QueryWrapper<>();
        communityPictureQueryWrapper.lambda().eq(ZfCommunityPicture::getType, type).eq(ZfCommunityPicture::getCommunityId, communtyId);
        List<ZfCommunityPicture> list = baseMapper.selectList(communityPictureQueryWrapper);
        //2、删除oss 图片
        for (ZfCommunityPicture pic : list
        ) {
            //1、删除oss 中的图片资源
            ossUtil.deleteFile(Constants.BUCKET_COMMUNITY, pic.getPath());
        }
        return baseMapper.delete(communityPictureQueryWrapper);

    }

    public Response communityPic(MultipartFile[] files, HttpServletRequest request) {
        try {
            List<Map<String, String>> pictureList = new ArrayList<>();
            // 1 图片上传
            if (files != null && files.length > 0) {
                // 如果是封面图先查询封面是否已经存在
                int type = Integer.parseInt(request.getParameter("type"));
                if (type == 0) {
                    this.delCommunityPicture(Long.parseLong(request.getParameter("cid")), type);

                }
                for (MultipartFile file : files
                ) {
                    Map<String, String> map = ossUtil.uploadObject2OSS(file, Constants.BUCKET_COMMUNITY, Constants.FOLDER_COMMUNITY + "/" + request.getParameter("cid"));
                    log.info("小区图片上传返回信息-----{}", JSONObject.toJSONString(map));
                    if (map != null) {
                        ZfCommunityPicture communityPicture = new ZfCommunityPicture();
                        communityPicture.setCommunityId(Long.parseLong(request.getParameter("cid")));
                        communityPicture.setPath(map.get("path"));
                        communityPicture.setUrl(map.get("url"));
                        communityPicture.setType(type);
                        // 保存图片信息
                        Long id = this.addCommunityPic(communityPicture);
                        Map<String, String> picMap = new HashMap<>();
                        picMap.put("id", String.valueOf(id));
                        picMap.put("url", map.get("url"));
                        pictureList.add(picMap);
                    }
                }

                return Response.success(pictureList);
            } else {
                return Response.error("请上传图片");
            }

        } catch (Exception e) {
            return Response.error("上传失败");
        }
    }

}
